<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="" prop="status">
        <el-radio-group @change="handleQuery" v-model="queryParams.status" >
          <el-radio-button label="待审核" value="DRAFT" />
          <el-radio-button label="已审核" value="CHECkED" />
          <el-radio-button label="已记账" value="RECORDED" />
        </el-radio-group>
      </el-form-item>
      <el-form-item label="年" prop="yearValue">
        <el-input
          v-model="queryParams.yearValue"
          placeholder="请输入年份和月份"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="月份" prop="monthValue">
        <el-input
            v-model="queryParams.monthValue"
            placeholder="请输入月份"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['project:FinRecordVoucher:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['project:FinRecordVoucher:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" default-expand-all :data="FinRecordVoucherList" @selection-change="handleSelectionChange" size="small">
      <el-table-column type="expand">
        <template #default="props">
          <div>
            <el-table :data="props.row.itemList" :border="true" size="small">
              <el-table-column label="凭证号" align="center" prop="recordNo" width="100"/>
              <el-table-column label="日期" align="center" prop="recordDate" width="180">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.recordDate, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="摘要" align="center" prop="description" />
              <el-table-column label="科目代码" align="center" prop="subjectCode" width="120"/>
              <el-table-column label="科目" align="center" prop="subjectName" >
                <template #default="scope">
                  <samp v-if="scope.row.subjectParentName">{{ scope.row.subjectParentName }}-></samp>{{ scope.row.subjectName }}
                </template>
              </el-table-column>
              <el-table-column label="借方金额" align="center" prop="jieAmount"  width="120">
                <template #default="scope">
                  <span class="money" v-if="scope.row.jieAmount>0">{{ scope.row.jieAmount }}</span>
                  <span v-else></span>
                </template>
              </el-table-column>
              <el-table-column label="贷方金额" align="center" prop="daiAmount" width="120">
                <template #default="scope">
                  <span class="money" v-if="scope.row.daiAmount>0">{{ scope.row.daiAmount }}</span>
                  <span v-else></span>
                </template>
              </el-table-column>
              <el-table-column label="年份和月份" align="center" prop="yearAndMonth" width="100"/>
            </el-table>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="ID" align="center" prop="id" width="80"/>
      <el-table-column label="期间" align="center" prop="yearAndMonth" width="120"/>
      <el-table-column label="凭证字" align="center" prop="recordTag" width="100"/>
      <el-table-column label="凭证号" align="center" prop="recordNo" width="80"/>
      <el-table-column label="借方金额" align="center" prop="jieAmount" />
      <el-table-column label="贷方金额" align="center" prop="daiAmount" />
      <el-table-column label="状态" align="center" prop="status" >
        <template #default="scope">
         <FinRecordVoucherStatus :status-val="scope.row.status"></FinRecordVoucherStatus>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" />

      <el-table-column label="创建时间" align="center" prop="recordDate" width="160">
        <template #default="scope">
          <span>{{ parseTime(scope.row.recordDate, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核人" align="center" prop="createBy" />
      <el-table-column label="审核时间" align="center" prop="recordDate" width="160">
        <template #default="scope">
          <span>{{ parseTime(scope.row.recordDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="记账人" align="center" prop="createBy" />

      <el-table-column label="记账时间" align="center" prop="recordDate" width="160">
        <template #default="scope">
          <span>{{ parseTime(scope.row.recordDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" size="small" icon="Edit" @click="goToEdit(scope.row,true)" v-if="scope.row.status=='DRAFT'"
                     v-hasPermi="['project:FinRecordVoucher:edit']">审核</el-button>
          <el-button link type="primary" size="small" icon="Edit" @click="goToEdit(scope.row,false)" v-if="scope.row.status=='CHECKED'"
                     v-hasPermi="['project:FinRecordVoucher:edit']">反审核</el-button>
          <el-button link type="primary" size="small" icon="Edit" @click="goToEdit(scope.row,true)" v-if="scope.row.status=='CHECKED'"
                     v-hasPermi="['project:FinRecordVoucher:edit']">记账</el-button>
          <el-button link type="primary" size="small" icon="Edit" @click="goToEdit(scope.row,false)" v-if="scope.row.status=='RECORDED'"
                     v-hasPermi="['project:FinRecordVoucher:edit']">反记账</el-button>
          <el-button link type="primary" size="small" icon="Edit" @click="goToEdit(scope.row)"
                     v-hasPermi="['project:FinRecordVoucher:edit']">详情</el-button>
          <el-button link type="primary" size="small" icon="Delete" v-if="scope.row.status=='DRAFT'" @click="goToEdit(scope.row)"
                     v-hasPermi="['project:FinRecordVoucher:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改记账凭证对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="FinRecordVoucherRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="凭证时间" prop="recordDate">
          <el-date-picker clearable
            v-model="form.recordDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择凭证时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="凭证字" prop="recordTag">
          <el-input v-model="form.recordTag" placeholder="请输入凭证字" />
        </el-form-item>
        <el-form-item label="借方金额" prop="jieAmount">
          <el-input v-model="form.jieAmount" placeholder="请输入借方金额" />
        </el-form-item>
        <el-form-item label="贷方金额" prop="daiAmount">
          <el-input v-model="form.daiAmount" placeholder="请输入贷方金额" />
        </el-form-item>
        <el-form-item label="年份和月份" prop="yearAndMonth">
          <el-input v-model="form.yearAndMonth" placeholder="请输入年份和月份" />
        </el-form-item>
        <el-form-item label="账套id" prop="packageId">
          <el-input v-model="form.packageId" placeholder="请输入账套id" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="FinRecordVoucher">
import {
  listFinRecordVoucher,
  getFinRecordVoucher,
  delFinRecordVoucher,
  addFinRecordVoucher,
  updateFinRecordVoucher,
  checkFinRecordVoucher, recordFinRecordVoucher, cancelRecordFinRecordVoucher
} from "@/api/project/FinRecordVoucher";
import FinRecordVoucherStatus from "@/components/enumShow/FinRecordVoucherStatus.vue";

const { proxy } = getCurrentInstance();
const channelUpdateList = new BroadcastChannel("updateFinRecordVoucherList");

channelUpdateList.onmessage = function (e) {
  console.log("on message update list");
  getList();
}

onUnmounted(() => {
  channelUpdateList.close();
});


const FinRecordVoucherList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 50,
    recordDate: null,
    recordTag: null,
    yearValue: null,
    monthValue: null,
    yearAndMonth: null,
    status: null,
    packageId: null,
  },
  rules: {
    recordDate: [
      { required: true, message: "凭证时间不能为空", trigger: "blur" }
    ],
    recordNo: [
      { required: true, message: "凭证号不能为空", trigger: "blur" }
    ],
    yearValue: [
      { required: true, message: "年份不能为空", trigger: "blur" }
    ],
    monthValue: [
      { required: true, message: "月份不能为空", trigger: "blur" }
    ],
    yearAndMonth: [
      { required: true, message: "年份和月份不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
    packageId: [
      { required: true, message: "账套id不能为空", trigger: "blur" }
    ],
    createId: [
      { required: true, message: "创建者ID不能为空", trigger: "blur" }
    ],
    updateId: [
      { required: true, message: "更新者ID不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询记账凭证列表 */
function getList() {
  loading.value = true;
  listFinRecordVoucher(queryParams.value).then(response => {
    FinRecordVoucherList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    recordDate: null,
    recordTag: null,
    recordNo: null,
    jieAmount: null,
    daiAmount: null,
    yearValue: null,
    monthValue: null,
    yearAndMonth: null,
    status: null,
    packageId: null,
    createId: null,
    createBy: null,
    createTime: null,
    updateId: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  proxy.resetForm("FinRecordVoucherRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  proxy.$router.push({
    path: '/finTotal/FinRecordVoucherCreate',
  });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getFinRecordVoucher(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改记账凭证";
  });
}

function goToEdit(row){
  proxy.$router.push({
    path: '/finTotal/FinRecordVoucherCreate',
    query: { id: row.id }
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["FinRecordVoucherRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateFinRecordVoucher(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addFinRecordVoucher(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除记账凭证编号为"' + _ids + '"的数据项？').then(function() {
    return delFinRecordVoucher(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('project/FinRecordVoucher/export', {
    ...queryParams.value
  }, `FinRecordVoucher_${new Date().getTime()}.xlsx`)
}

getList();
</script>
